﻿
@{
    Layout = "";
}
<style>
    .ngdialog.ngdialog-theme-plain .ngdialog-content {
        width: 45% !important;
    }

</style>


<div ng-controller="UserEditController">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                <form name="formValidate" ng-submit="submitForm()" novalidate="" class="form-validate form-horizontal">
                    <!-- START panel-->
                    <div class="panel panel-default" ng-class="{ 'whirl standard': isLoading,'': isLoading }">
                        <div class="panel-body">
                            <fieldset class="b0">
                                <legend>{{Employee.Id == 0 || Employee.Id == null ? '添加员工' : '修改员工信息'}}</legend>
                            </fieldset>
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">用户名</label>
                                    <div class="col-sm-4">
                                        <input type="text" name="EmployeeName" required="" ng-model="Employee.UserName" class="form-control" maxlength="30" />
                                        <span ng-show="validateInput('EmployeeName', 'required')" class="text-danger">请输入用户名</span>
                                        <span ng-show="IsRightName" class="text-danger">用户名只能为英文或数字</span>
                                    </div>
                                    <div class="col-sm-4">
                                        <h4 class="text-danger">*</h4>
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">姓名</label>
                                    <div class="col-sm-4">
                                        <input type="text" name="EmployeeDisplayName" required="" ng-model="Employee.RealName" class="form-control" maxlength="30" />
                                        <span ng-show="validateInput('EmployeeDisplayName', 'required')" class="text-danger">请输入姓名</span>
                                    </div>
                                    <div class="col-sm-4">
                                        <h4 class="text-danger">*</h4>
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">电话</label>
                                    <div class="col-sm-4">
                                        <input type="text" name="Phone" required="" ng-model="Employee.Phone" class="form-control" maxlength="50" ng-change="getPhoneLength(Employee.Phone)" />
                                        <span ng-show="validateInput('Phone', 'required')" class="text-danger">请输入电话号码</span>
                                        <span ng-show="IsRightPhone" class="text-danger">请输入正确电话号码</span>
                                    </div>
                                    <div class="col-sm-4">
                                        <h4 class="text-danger">*</h4>
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">邮箱</label>
                                    <div class="col-sm-4">
                                        <input type="text" name="EmployeeEmail" ng-model="Employee.Email" class="form-control" maxlength="30" />
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">分组</label>

                                    <div class="col-sm-4" >
                                        
                                        @*<select ng-options="employeeDepartment.Id as employeeDepartment.GroupName for employeeDepartment in EmployeeDepartmentList" ui-select2 ng-model="Employee.GroupId" class="form-control" name="MallDepartmentId" required="" multiple="multiple" id="sel_menu2" style="width:180px;">
                                            <option value="">请选择分组</option>
                                        </select>*@

                                        @*<span ng-show="validateInput('MallDepartmentId', 'required')" class="text-danger">请选择分组</span>*@
                                        
                                        <div ng-repeat="item in EmployeeDepartmentList">
                                            <input type="checkbox" ng-checked="isSelected(item.Id)" required="" name ="Authority" value="item.Id"  ng-click="updateSelection($event,item.Id)" >{{item.GroupName}}
                                            
                                        </div>
                                        <div id="Authority"></div>
                                        
                                    </div>

                                    <div class="col-sm-4">
                                        <h4 class="text-danger">*</h4>
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">图片选择</label>
                                    <div class="col-sm-3">
                                        <div class="imgcrop-preview" uploader="uploader">
                                            <img ng-src="{{myCroppedImage}}" style="max-width: 100%; max-height: 100%" onerror="javascript: this.src = '/Content/img/default.png';" />
                                            <input id="fileInput" type="file" style="display: none;" nv-file-select="" uploader="uploader" />
                                        </div>
                                        <div>
                                            <div style="" class="progress progress-xs" ng-show="uploading">
                                                <div role="progressbar" ng-style="{ 'width': uploader.progress + '%' }" class="progress-bar"></div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-sm-1">
                                        <button type="button" class="mb-sm btn btn-info" ng-click="selectImage()">
                                            图片选择
                                        </button>
                                    </div>
                                    <div class="col-sm-4">
                                        <h4 class="text-danger">*&nbsp;&nbsp;建议尺寸：320×320 </h4>
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset ng-if="Employee.Id == 0 || Employee.Id == null">
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">登入密码</label>
                                    <div class="col-sm-4">
                                        <input type="password" name="LoginPassword" required="" ng-model="Employee.Password" class="form-control" maxlength="20" ng-change="getPwdLength(Employee.Password)" />
                                        <span ng-show="validateInput('LoginPassword', 'required')" class="text-danger">请输入密码</span>
                                        <span ng-show="IsEnoughPassword" class="text-danger">密码长度不足，最少6位，最多20位</span>
                                    </div>
                                    <div class="col-sm-4">
                                        <h4 class="text-danger">*</h4>
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset ng-if="Employee.Id == 0 || Employee.Id == null">
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">确认密码</label>
                                    <div class="col-sm-4">
                                        <input type="password" name="SureLoginPassword" required="" ng-model="SureEmployee.SureLoginPassword" class="form-control" maxlength="20" ng-change="noShowDanger(SureEmployee.SureLoginPassword)" />
                                        <span ng-show="validateInput('SureLoginPassword', 'required')" class="text-danger">请输入确认密码</span>
                                        <span ng-show="DifferentPassWord" class="text-danger">两次密码不一致</span>
                                    </div>
                                    <div class="col-sm-4">
                                        <h4 class="text-danger">*</h4>
                                    </div>
                                </div>
                            </fieldset>
                        </div>
                        <div class="panel-footer text-right">
                            <button type="button" class="btn btn-warning" ng-click="cancel()">返回列表</button>
                            <button type="button" class="btn btn-primary" ng-click="serveMessage()">保存</button>
                        </div>
                    </div>
                    <!-- END panel-->
                </form>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    App.controller('UserEditController', ["$scope", "$state", "$http", "$stateParams", "Notify", "$filter", "FileUploader", '$timeout',
        function ($scope, $state, $http, $stateParams, Notify, $filter, FileUploader, $timeout) {
            'use strict';
            $scope.isLoading = true;
            $scope.DifferentPassWord = false;
            $scope.IsRightPhone = false;
            $scope.IsCheckAuthority = false;
            $scope.IsRightName = false;
            $scope.SureEmployee = [];

            $scope.IsEnoughPassword = false;
            $scope.validateInput = function (name, type) {
                var input = $scope.formValidate[name];                
                return (input.$dirty || $scope.submitted) && input.$error[type];
            };

            $scope.AuthorityGroup = new Array();
            $scope.checked = [];
            //数据初始化
            $http.post("/User/UserEdit", { Id: $stateParams.Id }).then(function (response) {
                
                $scope.Employee = angular.copy(response.data.userInfo);
                if ($scope.Employee == null) {
                    $scope.Employee = {};
                    $scope.Employee.Roles = [];
                }
                
                //console.log($scope.Employee);
                
                $scope.EmployeeDepartmentList = angular.copy(response.data.groupList);
                
                //var group = document.getElementById("Group");
                
                $scope.AuthorityGroup = response.data.userInfo.AuthorityGroup.split(",");
                
                $scope.myCroppedImage = '/Images/'+$scope.Employee.Picture;
                $scope.isLoading = false;
            });
            //权限显示选择项            
            $scope.isSelected = function (id) {
                return $scope.AuthorityGroup.indexOf(id.toString()) >= 0;
                //将result与checkbox的当前id即value值匹配
                //有就返回的true，没有就返回false
            };
            
            $scope.updateSelection = function ($event, id) {

                var checkbox = $event.target;
                var checked = checkbox.checked;
                if (checked) {
                    $scope.AuthorityGroup.push(id.toString());
                } else {
                    var idx = $scope.AuthorityGroup.indexOf(id.toString());
                    $scope.AuthorityGroup.splice(idx, 1);                    
                }
                
                if ($scope.AuthorityGroup.length > 0) {
                    $('#validateAuthority').remove();
                } else {
                    $('#Authority').append("<span class='text-danger' id='validateAuthority'>请选择分组</span>");
                }
            };
            

            //不显示密码不一致提示
            $scope.noShowDanger = function (surePassword) {
                if (surePassword == null) {
                    $scope.DifferentPassWord = false;
                }
            }

            //获取密码长度
            $scope.getPwdLength = function (password) {
                if (password == null) {
                    $scope.passwodrLen = 0;
                    $scope.IsEnoughPassword = false;
                }
                else {
                    $scope.passwodrLen = password.replace(/[^x00-xff]/g, "01").length;
                }
            };

            //获取电话码长度
            $scope.getPhoneLength = function (phone) {
                if (phone == null) {
                    $scope.phoneLen = 0;
                    $scope.IsRightPhone = false;
                }
                else {
                    $scope.phoneLen = phone.replace(/[^x00-xff]/g, "01").length;
                }
            };


            // 保存点击
            $scope.serveMessage = function () {
                alert($scope.AuthorityGroup);
                $scope.submitted = true;
                //判断号码
                if ($scope.phoneLen >= 1) {
                    var testPhoneNum = /^1[3578][0-9]{9}$/;
                    if (testPhoneNum.test($scope.Employee.Phone) === false) {
                        $scope.IsRightPhone = true;
                        return false;
                    } else { $scope.IsRightPhone = false; }
                }

                var testname = /^[\da-zA-Z]+$/;
                if (testname.test($scope.Employee.UserName) == false) {
                    $scope.IsRightName = true;
                    return false;
                } else { $scope.IsRightName = false; }

                if ($scope.Employee.Id == 0 || $scope.Employee.Id == null) {
                    //判断密码长度
                    if ($scope.passwodrLen < 6) {
                        $scope.DifferentPassWord = false;
                        $scope.IsEnoughPassword = true;
                        return false;
                    } else { $scope.IsEnoughPassword = false; }
                    //判断两次密码是否输入一致
                    if ($scope.SureEmployee.SureLoginPassword !== $scope.Employee.Password) {
                        $scope.DifferentPassWord = true;
                        return false;
                    } else {
                        $scope.DifferentPassWord = false;
                    }
                }
                
                //多个权限
                if ($scope.AuthorityGroup.toString() == '')
                {
                    $('#Authority').append("<span class='text-danger' id='validateAuthority'>请选择分组</span>");
                    return;
                } else {
                    $('#validateAuthority').remove();
                }

                if ($scope.AuthorityGroup.length > 0) {
                    $scope.Employee.GroupId = $scope.AuthorityGroup[0];
                }
                
                
                $scope.Employee.AuthorityGroup = $scope.AuthorityGroup.toString();

                $scope.isLoading = true;
                if ($scope.formValidate.$valid) {
                    $http.post("/User/UserEditSubmit", $scope.Employee).then(function (returnData) {
                        if (returnData.data.isSuccess) {
                            Notify.alert('操作成功!', { status: 'success' });
                            $state.go("app.usermanage");
                        } else {
                            Notify.alert(returnData.data.msg, { status: 'warning' });
                            $scope.isLoading = false;
                        }
                    });

                } else {
                    $scope.isLoading = false;
                }
            };

            //返回列表
            $scope.cancel = function () {
                $state.go("app.usermanage");
            }
            
            //-------------图片选择相关
            $scope.selectImage = function () {
                $("#fileInput").click();
                $("#fileInput").on('change', function (e) {
                    //e.currentTarget.files 是一个数组，如果支持多个文件，则需要遍历
                    $scope.file = e.currentTarget.files[0];
                    
                });
            };

            var handleFileSelect = function (evt) {
                var file = $scope.uploadSelectFile = evt.currentTarget.files[0];
                if (!evt.currentTarget.files[0] || ! /image\/\w+/.test(evt.currentTarget.files[0].type)) {
                    Notify.alert('请选择图像文件', { status: 'warning' });
                    return false;
                }
                if (file.size > 1 * 1024 * 1024) {
                    Notify.alert('图片大小不能大于1MB', { status: 'warning', timeout: 3000 });
                    $scope.uploadSelectFile = null;
                    return false;
                }
                var reader = new FileReader();
                reader.onload = function (evt) {
                    $scope.$apply(function ($scope) {
                        $scope.myCroppedImage = evt.target.result;
                    });
                };
                if (file)
                    reader.readAsDataURL(file);
            };

            angular.element(document.querySelector('#fileInput')).on('change', handleFileSelect);
            var uploader = $scope.uploader = new FileUploader({
                url: '/User/UpLoadProcess',
                formdata: {
                    file: $scope.file
                }
                
            });
            uploader.filters.push({
                name: 'customFilter',
                fn: function (item /*{File|FileLikeObject}*/, options) {
                    return this.queue.length < 10;
                }
            });

            // CALLBACKS

            uploader.onWhenAddingFileFailed = function (item /*{File|FileLikeObject}*/, filter, options) {
                console.info('onWhenAddingFileFailed', item, filter, options);
            };
            uploader.onAfterAddingFile = function (fileItem) {
                if ($scope.uploadSelectFile && /image\/\w+/.test($scope.uploadSelectFile.type)) {
                    $scope.uploading = true;
                    fileItem.upload();
                }
                console.info('onAfterAddingFile', fileItem);
            };
            uploader.onAfterAddingAll = function (addedFileItems) {
                $scope.uploader.progress = 0;
                console.info('onAfterAddingAll', addedFileItems);
            };
            uploader.onBeforeUploadItem = function (item) {
                console.info('onBeforeUploadItem', item);
            };
            uploader.onProgressItem = function (fileItem, progress) {
                
                console.info('onProgressItem', fileItem, progress);
                
            };
            uploader.onProgressAll = function (progress) {

                //  console.info('onProgressAll', progress);
            };
            uploader.onSuccessItem = function (fileItem, response, status, headers) {
                
                $("#fileInput").val("");
                $scope.uploader.progress = 0;
                $scope.pic = response.pic;
                $scope.Employee.Picture = response.filename;
                console.info('onSuccessItem', fileItem, response, status, headers);
            };
            uploader.onErrorItem = function (fileItem, response, status, headers) {
                console.info('onErrorItem', fileItem, response, status, headers);
            };
            uploader.onCancelItem = function (fileItem, response, status, headers) {
                console.info('onCancelItem', fileItem, response, status, headers);
            };
            uploader.onCompleteItem = function (fileItem, response, status, headers) {
                console.info('onCompleteItem', fileItem, response, status, headers);
            };
            uploader.onCompleteAll = function () {
                $scope.uploading = false;
            };
        }]);
</script>
